<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px"
    >
      <el-form-item label="医生姓名" prop="name">
        <el-autocomplete
          popper-class="my-autocomplete"
          class="inline-input"
          v-model="queryParams.userName"
          :fetch-suggestions="querySearchAsync"
          placeholder="请输入医生姓名"
          @keyup.enter.native="handleQuery"
        ><i
          class="el-icon-edit el-input__icon"
          slot="suffix"
        >
        </i>
          <template slot-scope="{ item }">
            <div class="name" >{{ item.value = item.userName }}</div>
            <div class="idCard">{{ item.idCard }}</div>
          </template>
        </el-autocomplete>
      </el-form-item>
      <!--      <el-form-item label="医生姓名" prop="userId">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.userName"-->
      <!--          placeholder="请输入医生姓名"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="时间间隔" prop="timeInterval">
        <el-input
          v-model="queryParams.timeInterval"
          placeholder="请输入时间间隔"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="规则类型" prop="timeInterval">
        <el-select v-model="queryParams.ruleType" placeholder="请选择规则类型">
          <el-option
            v-for="dict in dict.type.rule_type"
            :key="dict.value"
            :label="dict.label"
            :value="Number(dict.value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['rule:rule:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['rule:rule:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['rule:rule:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['rule:rule:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ruleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="编号" align="center">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="医生姓名" align="center" prop="userName"/>
      <el-table-column label="规则类型" align="center" prop="ruleType">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.rule_type"
            :value="scope.row.ruleType"
          ></dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="时间间隔" align="center" prop="timeInterval"/>
      <el-table-column label="开始时间" align="center" prop="startTime" width="180"/>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180"/>
      <el-table-column label="挂号数" align="center" prop="num" width="180"/>
      <el-table-column label="是否启用" align="center" prop="isEnable">
        <template slot-scope="scope">
          <!--          <el-tag v-if="scope.row.isEnable === 1" type="success">是</el-tag>-->
          <!--          <el-tag v-else-if="scope.row.isEnable === 0" type="danger">否</el-tag>-->
          <el-button v-if="scope.row.isEnable === 1" type="success" icon="el-icon-check"
                     @click="handleButton(scope.row)" circle
          />
          <el-button v-if="scope.row.isEnable === 0" type="danger" icon="el-icon-remove"
                     @click="handleButton(scope.row)" circle
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['rule:rule:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['rule:rule:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增规则模块对话框 -->
    <el-dialog :title="title" :visible.sync="openInsert" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="医生姓名" prop="userName">
          <el-autocomplete
            popper-class="my-autocomplete"
            class="inline-input"
            v-model="form.userName"
            :fetch-suggestions="querySearchAsync"
            placeholder="请输入医生姓名"
            @blur="handleBlur(form.userName)"
            @select="handleSelect"
          >
            <template slot-scope="{ item }">
              <div class="name">{{ item.value = item.userName }}</div>
              <div class="idCard">{{ item.idCard }}</div>
            </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item label="规则类型" prop="userId">
          <el-select v-model="form.ruleType" placeholder="请选择">
            <el-option
              v-for="dict in dict.type.rule_type"
              :key="dict.value"
              :label="dict.label"
              :value="Number(dict.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="时间间隔" prop="timeInterval">
          <!--          <el-input v-model="form.timeInterval" placeholder="请输入时间间隔"/>-->
          <el-input-number v-model="form.timeInterval" :step="10" :min="10" :max="180"/>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-time-select
            v-model="form.startTime"
            :picker-options="{
                start: '08:30',
                step: '00:30',
                end: '18:30'
             }"
            placeholder="选择时间"
          >
          </el-time-select>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-time-select
            v-model="form.endTime"
            :picker-options="{
                start: '08:30',
                step: '00:30',
                end: '18:30'
             }"
            placeholder="选择时间"
          >
          </el-time-select>
        </el-form-item>
        <el-form-item label="挂号数" prop="num">
          <el-input-number v-model="form.num" :min="1" :max="10"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改规则模块对话框 -->
    <el-dialog :title="title" :visible.sync="openUpdate" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="医生姓名" prop="userName">
          <el-input disabled v-model="form.userName"/>
        </el-form-item>
        <el-form-item label="规则类型" prop="userId">
          <el-select v-model="form.ruleType" placeholder="请选择">
            <el-option
              v-for="dict in dict.type.rule_type"
              :key="dict.value"
              :label="dict.label"
              :value="Number(dict.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="时间间隔" prop="timeInterval">
          <!--          <el-input v-model="form.timeInterval" placeholder="请输入时间间隔"/>-->
          <el-input-number v-model="form.timeInterval" :step="10" :min="10" :max="180"/>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-time-select
            v-model="form.startTime"
            :picker-options="{
                start: '08:30',
                step: '00:30',
                end: '18:30'
             }"
            placeholder="选择时间"
          >
          </el-time-select>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-time-select
            v-model="form.endTime"
            :picker-options="{
                start: '08:30',
                step: '00:30',
                end: '18:30'
             }"
            placeholder="选择时间"
          >
          </el-time-select>
        </el-form-item>
        <el-form-item label="挂号数" prop="num">
          <el-input-number v-model="form.num" :min="1" :max="10"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style lang="scss">
.my-autocomplete {
  li {
    line-height: normal;
    padding: 7px;

    .name {
      text-align: center;
      text-overflow: ellipsis;
      overflow: hidden;
    }

    .idCard {
      text-align: center;
      font-size: 12px;
      color: #b4b4b4;
    }

    .highlighted .idCard {
      text-align: center;
      color: #ddd;
    }
  }
}
</style>

<script>
import { addRule, delRule, getRule, listRule, updateEnable, updateRule } from '@/api/rule/rule'
import { parseTime } from '@/utils/ruoyi'
import { getDoctorNameAndId } from '@/api/doctorinfo/doctorinfo'

export default {
  name: 'Rule',
  //数据字典
  dicts: ['rule_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 规则模块表格数据
      ruleList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      openInsert: false,
      openUpdate: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        ruleType: null,
        timeInterval: null,
        startTime: null,
        endTime: null,
        num: null,
        isEnable: null,
        userName: null
      },
      // 医生姓名和id
      doctorNameAndId: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    }
  },
  created() {
    this.getDoctor()
    this.getList()
  },
  methods: {
    parseTime,
    /** 查询医生姓名和id */
    getDoctor() {
      getDoctorNameAndId().then(response => {
        this.doctorNameAndId = response.data
        console.log('this.doctorNameAndId', this.doctorNameAndId)
      })
    },
    /** 查询规则模块列表 */
    getList() {
      this.loading = true
      listRule(this.queryParams).then(response => {
        this.ruleList = response.rows
        this.total = response.total
        this.loading = false
      })
      console.log('this.ruleList', this.ruleList)
    },
    // 取消按钮
    cancel() {
      this.openUpdate = false
      this.openInsert = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        createTime: null,
        createUser: null,
        updateTime: null,
        updateUser: null,
        isDeleted: null,
        userId: null,
        userName: null,
        ruleType: null,
        timeInterval: null,
        startTime: null,
        endTime: null,
        isEnable: null,
        num: 1
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.queryParams.userName=null
      this.handleQuery()
    },
    handleBlur(val) {
      console.log('input Input value:', val)
      console.log('Doctor names:', this.doctorNameAndId.map(user => user.userName))
      const selectedUser = this.doctorNameAndId.find(user => user.userName === val)
      const id = selectedUser ? selectedUser.userId : null
      this.form.userId = id
      console.log('input Selected id:', id)
    },
    handleSelect(val) {
      console.log('select Input value:', val)
      console.log('Doctor idCard:', this.doctorNameAndId.map(user => user.idCard))
      this.form.userId = val.userId
      this.form.userName = val.userName
      console.log('select Selected id:', this.form.userId)
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.openInsert = true
      this.title = '添加规则模块'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getRule(id).then(response => {
        this.form = response.data
        this.openUpdate = true
        this.title = '修改规则模块'
      })
    },
    /** 修改是否启用 */
    handleButton(row) {
      const id = row.id
      //获取isEnable的值,并取反
      const isEnable = row.isEnable === 1 ? 0 : 1
      updateEnable(id, isEnable).then(response => {
        this.$modal.msgSuccess('状态修改成功')
        this.getList()
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRule(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.openUpdate = false
              this.getList()
            })
          } else {
            addRule(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.openInsert = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除规则模块编号为"' + ids + '"的数据项？').then(function() {
        return delRule(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('rule/rule/export', {
        ...this.queryParams
      }, `rule_${new Date().getTime()}.xlsx`)
    },
    querySearchAsync(queryString, cb) {
      const restaurants = this.doctorNameAndId
      const results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants

      // console.log('results', results)
      cb(results)
    },
    createStateFilter(queryString) {
      return (state) => {
        return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    }
  }
}
</script>
